//
//  SensorListViewController.m
//  wAudioShare
//
//  Created by Anson on 14-12-7.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "SensorListViewController.h"
#import "AutomationCell.h"
#import "CameraData.h"
#import "ChangeInfoDialog.h"
#import "Utitlity.h"

@interface SensorListViewController () <AutomationCellDelegate, changeDataDicDelegate, UIActionSheetDelegate>

@end

@implementation SensorListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title =@"Sensor";
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-load datasouce
-(NSArray *)loadPageData:(int)page
{
    [activity startAnimating];
    
    ipUrl = [Utitlity judgeipUrl];
    isLoaded = NO;
    //    __block int isLoaded = NO;
    
    if (ipUrl)
    {
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1",ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [activity stopAnimating];
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            //            NSMutableArray *result = [NSMutableArray array];
            NSMutableString *zids = [NSMutableString string];
            {
                isLoaded = YES;
                deviceList = responseObject[@"data"];
                NSLog(@"deviceList-----------:%@",deviceList);
                
                for (int i = 0; i< [deviceList count]; i ++)
                {
                    NSMutableDictionary *item = [[deviceList objectAtIndex:i] mutableCopy];
                    NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                    
                    if ( deviceType == 3 || deviceType == 4)
                    {
                        //8是窗帘类型 Device_Type_MOTOR, VALUE=0关  99开  -1停
                        [zids appendFormat:@"%@,",[item objectForKey:@"ZID"]];
                        [resultItem addObject:item];
                    }
                }
            }
            
            if ([resultItem count] > 0)
            {
                [super doneLoadingTableViewData:resultItem];
                self.ids = zids;
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        //        [[CMDDataProcessor sharedInstance] getDeviceListResultDataWithDataRecivedBlock:nil];
        [[CMDDataProcessor sharedInstance] getDeviceListResultDataWithDataRecivedBlock:^(id data) {
            
            if (!data || ![data isKindOfClass:[NSDictionary class]]) return;
            if ([data[@"state"] isEqualToString:@"Success"])
            {
                [activity stopAnimating];
                tcpResultItem = [[NSMutableArray alloc] init];
                //                NSMutableArray *result = [[NSMutableArray alloc] init];
                NSMutableString *zids = [[NSMutableString alloc] init];
                {
                    isLoaded = YES;
                    DLog(@"");
                    deviceList = data[@"data"];
                    NSLog(@"deviceList1111-----------:%@",deviceList);
                    for (int i = 0 ; i< [deviceList count]; i ++)
                    {
                        NSMutableDictionary *item = [[deviceList objectAtIndex:i] mutableCopy];
                        NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                        
                        if ( deviceType == 3 || deviceType == 4) {
                            //8是窗帘类型 Device_Type_MOTOR, VALUE=0关  99开  -1停
                            [zids appendFormat:@"%@,",[item objectForKey:@"ZID"]];
                            [tcpResultItem addObject:item];
                        }
                    }
                }
                
                if ([tcpResultItem count] > 0 )
                {
                    [super doneLoadingTableViewData:tcpResultItem];
                    self.ids = zids;
                }
            }
        }];
    }
    //再次请求数据
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!isLoaded)
        {
            NSLog(@"再次获取列表");
            [self loadPageData:1];
        }
    });
    
    return nil;
}

/*
#pragma mark-UITableView
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    static NSString *AutomationCellIdentifier = @"AutomationCellIdentifier";
    AutomationCell *cell = (AutomationCell*)[dataTableView dequeueReusableCellWithIdentifier:AutomationCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"AutomationCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.adelegate= self;
        cell.curtainCtrlView.hidden = YES;
    }
    NSMutableDictionary *rowData = [self.rows objectAtIndex:row];
    
    //    NSMutableDictionary *muDic = [rowData mutableCopy];
    strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = rowData[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
    [rowData setObject:appStr forKey:@"uuid"];
    [cell setCellData:rowData];
    
    //	NSUInteger row=[indexPath row];
    //    return [self.rows objectAtIndex:row];
    return cell;
}
*/
- (void)switcherOnChangedValue:(BOOL)swValue data:(NSDictionary *)data cell:(AutomationCell *)cell {
    
    ipUrl = [Utitlity judgeipUrl];
    NSString *zid = [data objectForKey:@"ZID"];
    if (ipUrl)
    {
        NSString *armVal = (swValue?@"true":@"false");
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Sensor.cgi?action=do_setarm&did=%@&arm=%@",ipUrl,zid, armVal];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([[[responseObject objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                NSMutableDictionary *newData = [NSMutableDictionary dictionaryWithDictionary:data];
                newData[@"Arm"] = armVal;
                NSUInteger index = [self.rows indexOfObject:data];
                if (index != NSNotFound) {
                    [self.rows replaceObjectAtIndex:index withObject:newData];
                    [dataTableView reloadData];
                }
                
            }else{
                
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
            [self toastMsg:error.localizedDescription];
        }];
    }
    
}



@end
